package ch.unisi.inf.gui.action;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;



/**
 * 
 * @author Mohamed.Mosa@lu.unisi.ch
 * This class displays a preview of the image selected while still
 * in the file chooser window.
 * 
 */

public final class ImagePreview extends JComponent implements PropertyChangeListener { 
    
	private File file = null;
    private ImageIcon preview = null;
    
    //Here we register the the changes
    public ImagePreview(JFileChooser fc) {
        setPreferredSize(new Dimension(200, 100));
        fc.addPropertyChangeListener(this);
    }

    public final void loadImage() {
        if (file == null) {
            preview = null;
            return;
        }

        ImageIcon temp = new ImageIcon(file.getPath());
        if (temp != null) {
            if (temp.getIconWidth() <= 50) {
                preview = new ImageIcon(temp.getImage().
           		getScaledInstance(100, -1, Image.SCALE_DEFAULT));
            } 
            else 
            if (temp.getIconWidth() > 50) {
                preview = new ImageIcon(temp.getImage().
           		getScaledInstance(150, -1, Image.SCALE_DEFAULT));
            } 
            else { 
                preview = temp;
            }
        }
    }

    public final void propertyChange(PropertyChangeEvent e) {
        boolean update = false;
        String proporty = e.getPropertyName();

        //If the directory changed, don't show an image.
        if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(proporty)) {
            file = null;
            update = true;

        //This method will show which file was selected
        } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(proporty)) {
            file = (File) e.getNewValue();
            update = true;
        }

        //Here I update the preview window 
        if (update) {
            preview = null;
            if (isShowing()) {
                loadImage();
                repaint();
            }
        }
    }

    //In this method the image icon is painted
    protected final void paintComponent(Graphics g) {
        if (preview == null) {
            loadImage();
        }
        if (preview != null) {
            int x = getWidth()/2 - preview.getIconWidth()/2;
            int y = getHeight()/2 - preview.getIconHeight()/2;

            if (y < 0) {
                y = 0;
            }
            if (x < 5) {
                x = 5;
            }
            preview.paintIcon(this, g, x, y);
        }
    }
}